#include <g-bios.h>
#include <core/cmd.h>
#include <sysconf.h>
#include <string.h>
#include <core/getopt.h>
#include <flash/part.h>
#include <core/bar.h>


const char *GuPartTypeToStr(UINT32 nType)
{
	switch(nType)
	{
	case PT_FREE:
		return PT_STR_FREE;

	case PT_BL_GBIOS:
		return PT_STR_GBIOS;

	case PT_OS_LINUX:
		return PT_STR_LINUX;

	case PT_OS_WINCE:
		return PT_STR_WINCE;

	case PT_FS_RAMDISK:
		return PT_STR_RAMDISK;

	case PT_FS_CRAMFS:
		return PT_STR_CRAMFS;

	case PT_FS_JFFS2:
		return PT_STR_JFFS2;

	case PT_FS_YAFFS:
		return PT_STR_YAFFS;

	case PT_FS_YAFFS2:
		return PT_STR_YAFFS2;

	default:
		return "Unknown";
	}
}


const char *GuPartGetName(const struct PartAttr *pAttr)
{
	if (pAttr->szPartName[0] == '\0')
	 	return GuPartTypeToStr(pAttr->nPartType);

	return pAttr->szPartName;
}

// fixme
int GuPartShow(const struct Flash *pFlash)
{
	struct PartAttr vPartAttr[MAX_FLASH_PARTS];
	UINT32 nParts, nIndex, nRootIndex;
	char *pBar = "----------------------------------------------------------------";
	int nPartNum;


	nPartNum = pFlash->pPartInfo->nParts;

	//If pFlash->pPartInfo == NULL;

	if (NULL == pFlash)
	{
		printf("ERROR: fail to open a flash!\n");
		return -ENODEV;
	}

	nParts = nPartNum;

	GuPartTabRead(pFlash, vPartAttr, nParts);

	if (0 == nParts)
	{
		printf("There is no partition created on this flash!\n");
		return 0;
	}

	nRootIndex = GuSysConfGetRoot();

	printf("\n Parition List: (on %s)\n", pFlash->szName);
	printf("%s\n", pBar);
	printf(" Index     Start         End      Size      Type       Name\n");
	printf("%s\n", pBar);

	for (nIndex = 0; nIndex < nParts; nIndex++)
	{
		char szPartIdx[8], szPartSize[16];
	
		sprintf(szPartIdx, "%d%c",
			nIndex, (nIndex == nRootIndex) ? '*' : ' ');

		GuValToHrStr(vPartAttr[nIndex].ulPartSize, szPartSize);

		printf("   %-3s  0x%08x - 0x%08x  %-8s  %-8s  \"%s\"\n", 
			szPartIdx,
			vPartAttr[nIndex].ulPartBase, 
			vPartAttr[nIndex].ulPartBase + vPartAttr[nIndex].ulPartSize, 
			szPartSize,
			GuPartTypeToStr(vPartAttr[nIndex].nPartType),
			GuPartGetName(&vPartAttr[nIndex])
			);
	}

	printf("%s\n", pBar);

	return nParts;
}

static int main(int argc, char *argv[])
{
	struct Flash *pFlash;
	UINT32 nFlashID;

	nFlashID = 0;

	while (pFlash = GuFlashOpen(nFlashID))
	{
		GuPartShow(pFlash);

		GuFlashClose(pFlash);

		nFlashID++;
	}

	return 0;
}


INSTALL_APPLICATION(partshow, main, "show flash partition");

